package com.kedll.library.util;

import android.app.Activity;
import android.os.Handler;
import android.widget.Toast;

import com.kedll.library.R;

import java.lang.ref.WeakReference;

/**
 * 按两次退出
 */
public class Exit {
    private boolean isExit = false;
    private WeakReference<Activity> mActivity;
    private Handler handler;

    public Exit(Activity mActivity) {
        this.mActivity = new WeakReference<>(mActivity);
    }

    private Toast toast;
    private Runnable task = new Runnable() {
        @Override
        public void run() {
            isExit = false;
        }
    };

    private void doExitInOneSecond() {
        isExit = true;
        if (handler == null) {
            handler = new Handler();
        }
        handler.postDelayed(task, 1000);
    }

    /**
     * 再按一次退出程序。
     */
    public void pressAgainExit() {
        Activity activity = mActivity.get();
        if (activity != null) {
            if (isExit) {
                handler.removeCallbacksAndMessages(null);
                handler = null;
                if (toast != null) {
                    toast.cancel();
                    toast = null;
                }
                activity.finish();
            } else {
                if (toast == null) {
                    toast = Toast.makeText(activity.getApplication(), R.string.string_exit_by_touch_again, Toast.LENGTH_LONG);
                }
                toast.show();
                doExitInOneSecond();
            }
        }
    }
}